package com.funsport.controller.web;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.funsport.common.Result;
import com.funsport.entity.PointOrder;
import com.funsport.service.IPointOrderService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

/**
 * Web端积分订单管理Controller
 */
@Slf4j
@RestController
@RequestMapping("/api/web/point/order")
@RequiredArgsConstructor
@Tag(name = "Web端积分订单管理")
@PreAuthorize("hasAnyRole('ADMIN', 'SUPER_ADMIN')")
public class WebPointOrderController {
    
    private final IPointOrderService pointOrderService;
    
    @Operation(summary = "获取所有订单列表")
    @GetMapping("/list")
    public Result<Page<PointOrder>> getAllOrders(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer pageSize,
            @RequestParam(required = false) String status,
            @RequestParam(required = false) Long userId
    ) {
        try {
            Page<PointOrder> result = pointOrderService.getAllOrders(page, pageSize, status, userId);
            return Result.success(result);
        } catch (Exception e) {
            log.error("获取订单列表失败: {}", e.getMessage(), e);
            return Result.error(e.getMessage());
        }
    }
    
    @Operation(summary = "获取订单详情")
    @GetMapping("/{id}")
    public Result<PointOrder> getOrderDetail(@PathVariable Long id) {
        try {
            PointOrder order = pointOrderService.getById(id);
            if (order == null) {
                return Result.error("订单不存在");
            }
            return Result.success(order);
        } catch (Exception e) {
            log.error("获取订单详情失败: {}", e.getMessage(), e);
            return Result.error(e.getMessage());
        }
    }
    
    @Operation(summary = "发货")
    @PostMapping("/ship")
    public Result<Void> ship(
            @RequestParam String orderNo,
            @RequestParam String shippingNo
    ) {
        try {
            pointOrderService.ship(orderNo, shippingNo);
            return Result.success();
        } catch (Exception e) {
            log.error("发货失败: {}", e.getMessage(), e);
            return Result.error(e.getMessage());
        }
    }
    
    @Operation(summary = "完成订单")
    @PostMapping("/complete")
    public Result<Void> complete(@RequestParam String orderNo) {
        try {
            pointOrderService.complete(orderNo);
            return Result.success();
        } catch (Exception e) {
            log.error("完成订单失败: {}", e.getMessage(), e);
            return Result.error(e.getMessage());
        }
    }
}

